﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Backend.DTO;
using System.Globalization;
using Backend.BLL;

namespace ReSeSSApplication
{
    public partial class RegisterUser : System.Web.UI.Page
    {
        UserBLL aUserBll = new UserBLL();
        UserDTO loggedInUserDTO = new UserDTO();
        UserDTO aUser = new UserDTO();

        protected void Page_Load(object sender, EventArgs e)
        {
            AlertSuccess.Visible = false;
            AlertError.Visible = false;
            UpdateUserButton.Visible = false;
            int editMode = Convert.ToInt32(IsEditMode.Value);

            loggedInUserDTO = (UserDTO)Session["LoggedInUserDTO"];
            RedirectUser(loggedInUserDTO);

            if (!IsPostBack)
            {
                PoppulateDropDowns();
            }

            if (editMode == 0)
            {
                try
                {
                    int editId = Convert.ToInt32(Request.QueryString["e"]);
                    if (editId > 0)
                    {
                        IsEditMode.Value = "1";
                        aUser = aUserBll.GetUserById(editId);

                        if (aUser != null)
                        {
                            txtLoginId.Text = aUser.LoginId;
                            txtPassword.Text = string.Empty;
                            txtConfirmPassword.Text = string.Empty;
                            txtFirstName.Text = aUser.FirstName;
                            txtLastName.Text = aUser.LastName;
                            txtEmail.Text = aUser.Email;

                            ddlMonth.SelectedValue = aUser.DateOfBirth.Month.ToString();
                            ddlDay.SelectedValue = aUser.DateOfBirth.Day.ToString();
                            ddlYear.SelectedValue = aUser.DateOfBirth.Year.ToString();

                            if (aUser.Gender == "Male")
                            {
                                rdoGenderMale.Checked = true;
                                rdoGenderFemale.Checked = false;
                            }
                            else if (aUser.Gender == "Female")
                            {
                                rdoGenderMale.Checked = false;
                                rdoGenderFemale.Checked = true;
                            }
                            else
                            {
                                rdoGenderMale.Checked = false;
                                rdoGenderFemale.Checked = false;
                            }

                            if (aUser.IsActive)
                            {
                                rdoIsActiveYes.Checked = true;
                                rdoIsActiveNo.Checked = false;
                            }
                            else
                            {
                                rdoIsActiveYes.Checked = false;
                                rdoIsActiveNo.Checked = true;
                            }

                            txtLoginId.Enabled = false;
                            RegisterUserButton.Visible = false;
                            UpdateUserButton.Visible = true;
                        }
                        else
                        {
                            AlertError.InnerText = "Invalid user to edit";
                            AlertError.Visible = false;
                        }
                    }
                }
                catch
                {
                    AlertError.InnerText = "Invalid user to edit";
                    AlertError.Visible = false;
                }
            }
        }

        protected void RegisterUserButton_Click(object sender, EventArgs e)
        {
            string loginId = txtLoginId.Text.Trim();
            string password = txtPassword.Text.Trim();
            string confirmPassword = txtConfirmPassword.Text.Trim();
            string firstName = txtFirstName.Text.Trim();
            string lastName = txtLastName.Text.Trim();
            DateTime dateOfBirth;
            string email = txtEmail.Text.Trim();
            int month = Convert.ToInt32(ddlMonth.SelectedItem.Value);
            int day = Convert.ToInt32(ddlDay.SelectedItem.Value);
            int year = Convert.ToInt32(ddlYear.SelectedItem.Value);
            string gender = string.Empty;
            bool isActive = false;
            string userType = "User";

            if (rdoGenderMale.Checked) { gender = rdoGenderMale.Text; }
            else if (rdoGenderFemale.Checked) { gender = rdoGenderFemale.Text; }

            if (rdoIsActiveYes.Checked) { isActive = true; }
            else if (rdoIsActiveNo.Checked) { isActive = false; }

            if (loginId == string.Empty || password == string.Empty || confirmPassword == string.Empty || firstName == string.Empty || lastName == string.Empty || email == string.Empty)
            {
                AlertError.InnerText = "Required field cannot be empty";
                AlertError.Visible = true;
                return;
            }

            if (password != confirmPassword)
            {
                AlertError.InnerText = "Confirm Password does not match with Password";
                AlertError.Visible = true;
                return;
            }

            try
            {
               dateOfBirth  = Convert.ToDateTime(year + "-" + month + "-" + day);
            }
            catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
                return;
            }

            UserDTO newUser = new UserDTO();
            newUser.LoginId = loginId;
            newUser.Password = password;
            newUser.FirstName = firstName;
            newUser.LastName = lastName;
            newUser.DateOfBirth = dateOfBirth;
            newUser.Gender = gender;
            newUser.Email = email;
            newUser.UserType = userType;
            newUser.RegisteredDate = DateTime.Now;
            newUser.IsActive = isActive;

            try
            {
                UserBLL aUserBll = new UserBLL();
                string userAddResult = aUserBll.AddUser(newUser);

                if (userAddResult != "success")
                {
                    AlertError.InnerText = userAddResult;
                    AlertError.Visible = true;
                    return;
                }
                else
                {
                    AlertSuccess.InnerText = "User registered successfully.";
                    AlertSuccess.Visible = true;
                    ClearRegisterUserForm();
                    return;
                }
            }
            catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
                return;
            }
        }

        protected void UpdateUserButton_Click(object sender, EventArgs e)
        {
            if (IsEditMode.Value.Trim() == "1")
            {
                txtLoginId.Enabled = false;
                RegisterUserButton.Visible = false;
                UpdateUserButton.Visible = true;

                string password = txtPassword.Text.Trim();
                string confirmPassword = txtConfirmPassword.Text.Trim();
                string firstName = txtFirstName.Text.Trim();
                string lastName = txtLastName.Text.Trim();
                DateTime dateOfBirth;
                string email = txtEmail.Text.Trim();
                int month = Convert.ToInt32(ddlMonth.SelectedItem.Value);
                int day = Convert.ToInt32(ddlDay.SelectedItem.Value);
                int year = Convert.ToInt32(ddlYear.SelectedItem.Value);
                string gender = string.Empty;
                bool isActive = false;

                if (rdoGenderMale.Checked) { gender = rdoGenderMale.Text; }
                else if (rdoGenderFemale.Checked) { gender = rdoGenderFemale.Text; }

                if (rdoIsActiveYes.Checked) { isActive = true; }
                else if (rdoIsActiveNo.Checked) { isActive = false; }

                if (firstName == string.Empty || lastName == string.Empty || email == string.Empty)
                {
                    AlertError.InnerText = "Required field cannot be empty";
                    AlertError.Visible = true;
                    return;
                }

                if (password != confirmPassword)
                {
                    AlertError.InnerText = "Confirm Password does not match with Password";
                    AlertError.Visible = true;
                    return;
                }

                try
                {
                    dateOfBirth = Convert.ToDateTime(year + "-" + month + "-" + day);
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                    return;
                }

                try
                {
                    aUser = aUserBll.GetUser(txtLoginId.Text);

                    if (!string.IsNullOrEmpty(password) && password != aUser.Password)
                    {
                        aUserBll.UpdateUser("Password", password, aUser.Id);
                    }
                    if (!string.IsNullOrEmpty(firstName) && firstName != aUser.FirstName)
                    {
                        aUserBll.UpdateUser("FirstName", firstName, aUser.Id);
                    }
                    if (!string.IsNullOrEmpty(lastName) && lastName != aUser.LastName)
                    {
                        aUserBll.UpdateUser("LastName", lastName, aUser.Id);
                    }
                    if (!string.IsNullOrEmpty(email) && email != aUser.Email)
                    {
                        aUserBll.UpdateUser("Email", email, aUser.Id);
                    }
                    if (dateOfBirth != aUser.DateOfBirth)
                    {
                        aUserBll.UpdateUser("DateOfBirth", dateOfBirth.Year + "-" + dateOfBirth.Month + "-" + dateOfBirth.Day, aUser.Id);
                    }
                    if (gender != aUser.Gender)
                    {
                        aUserBll.UpdateUser("Gender", gender, aUser.Id);
                    }
                    if (isActive != aUser.IsActive)
                    {
                        if (isActive)
                        {
                            aUserBll.UpdateUser("IsActive", "1", aUser.Id);
                        }
                        else
                        {
                            aUserBll.UpdateUser("IsActive", "0", aUser.Id);
                        }
                    }

                    AlertSuccess.InnerText = "User updated successfully";
                    AlertSuccess.Visible = true;
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                    return;
                }
            }
        }

        private void PoppulateDropDowns()
        {
            for (int i = 0; i <= 12; i++)
            {
                if (i == 0)
                {
                    ListItem aListItem = new ListItem("Select Month", "0");
                    ddlMonth.Items.Add(aListItem);
                }
                else
                {
                    ListItem aListItem = new ListItem(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i), i.ToString());
                    ddlMonth.Items.Add(aListItem);
                }
            }

            for (int i = 0; i <= 31; i++)
            {
                if (i == 0)
                {
                    ListItem aListItem = new ListItem("Select Day", "0");
                    ddlDay.Items.Add(aListItem);
                }
                else
                {
                    ddlDay.Items.Add(i.ToString());
                }
            }

            int startYear = DateTime.Now.Year;
            for (int i = startYear; i > (startYear - 100); i--)
            {
                if (i == startYear)
                {
                    ListItem aListItem = new ListItem("Select Year", "0");
                    ddlYear.Items.Add(aListItem);
                }

                ddlYear.Items.Add(i.ToString());
            }
        }

        private void ClearRegisterUserForm()
        {
            txtLoginId.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtConfirmPassword.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtEmail.Text = string.Empty;

            ddlMonth.SelectedValue = "0";
            ddlDay.SelectedValue = "0";
            ddlYear.SelectedValue = "0";

            rdoGenderMale.Checked = false;
            rdoGenderFemale.Checked = false;
            rdoIsActiveYes.Checked = false;
            rdoIsActiveNo.Checked = false;
        }

        protected void RedirectUser(UserDTO userDTO)
        {
            if (userDTO != null)
            {
                if (userDTO.UserType == "User")
                {
                    Response.Redirect("UserDashboard.aspx");
                }
            }
            else
            {
                Response.Redirect("Index.aspx");
            }
        }
    }
}